package com.platform.modules.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.Query;
import com.platform.modules.mall.dao.MallRuleDao;
import com.platform.modules.mall.entity.MallRuleEntity;
import com.platform.modules.mall.service.MallRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 商户平台活动规则Service实现类
 *
 * @author tech
 * @date 2020-08-08 11:13:13
 */
@Service("mallRuleService")
public class MallRuleServiceImpl extends ServiceImpl<MallRuleDao, MallRuleEntity> implements MallRuleService {


    @Autowired
    private JedisUtil jedisUtil;

    private static final String KEY="MallRuleServiceCache_";

    @Override
    public List<MallRuleEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.id");
        params.put("asc", false);
        Page<MallRuleEntity> page = new Query<MallRuleEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallRulePage(page, params));
    }

    @Override
    public boolean add(MallRuleEntity mallRule) {
        return this.save(mallRule);
    }

    @Override
    public boolean update(MallRuleEntity mallRule) {
        MallRuleEntity entity = this.getById(mallRule.getId());
        if (entity!=null){
            jedisUtil.delObject(KEY+entity.getType());
        }
        return this.updateById(mallRule);
    }

    @Override
    public boolean delete(String id) {
        MallRuleEntity entity = this.getById(id);
        if (entity!=null){
            jedisUtil.delObject(KEY+entity.getType());
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        for (String id:ids){
            MallRuleEntity entity = this.getById(id);
            if (entity!=null){
                jedisUtil.delObject(KEY+entity.getType());
            }
        }
        return this.removeByIds(Arrays.asList(ids));
    }


    @Override
    public MallRuleEntity getEntityByType(Integer type) {
        Object mallRule =jedisUtil.getObject(KEY+type);
        if (mallRule!=null){
            return (MallRuleEntity) mallRule;
        }
        MallRuleEntity entity = this.lambdaQuery().eq(MallRuleEntity::getType, type).one();
        if (entity!=null){
            this.jedisUtil.setObject(KEY+entity.getType(),entity);
        }
        return entity;
    }
}
